import pygame, random, sys
from pygame.locals import *

from pygame import *

import ConfigParser
import os.path
import cPickle

DATADIR = 'data'
DIALOG = (153, 170, 119)
RED = (255, 0, 0)
YELLOW = (204, 204, 0)
GREEN = (0, 255, 0)


def scaled_image_dict(name, description, typeOfImage, image, scale, x, y):
	Image = pygame.image.load(image)
	ImageRect = Image.get_rect()
	ImageDict = {  'name': name,
			'description': description,
			'typeOfimage': typeOfImage,
			'surface': pygame.transform.scale(Image, (ImageRect.width * scale, ImageRect.height * scale)),
			'rect': pygame.Rect(x * scale, y * scale, ImageRect.width * scale, ImageRect.height * scale),
		     }
	return ImageDict

def mouseOverIcon(MouseIconRect, interactiveIcons):
	collision = False
	cRect = False
	cName = False
	cType = False
	cDesc = False
	for i in interactiveIcons:
		if MouseIconRect.colliderect(i['rect']):
			collision = True
			cRect = i['rect']
			cName = i['name']
			cType = i['typeOfimage']
			cDesc = i['description']
			return (collision, cRect, cName, cType, cDesc)
	return (collision, cRect, cName, cType,  cDesc)


def drawText(text, font, colour, surface, x, y):
    textobj = font.render(text, 1, colour)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def generic_load(file, mandatory=True):
    """
generic_load() loads a data file.  Data files are all in Python-standard
ConfigParser format.  The 'id' of any object is the section of that object.
Fields that need to be lists are postpended with _list; this is stripped
from the actual name, and the internal entries are broken up by the pipe
("|") character.

On errors, if file is mandatory then quit, else raise exception. For syntax
parsing-related errors, always print error message. For IOErrors silently ignore
non-mandatory missing or otherwise unreadable files
"""

    config = ConfigParser.RawConfigParser()
    filename = os.path.join(DATADIR, file)
    try:
        config.readfp(open(filename, "r"))

    except IOError as reason:
        # Silently ignore non-mandatory missing files
        if mandatory:
            sys.stderr.write("Cannot read '%s': %s\nExiting\n" %  (filename, reason))
            sys.exit(1)
        else:
            raise

    except Exception as reason:
        # Always print parsing errors, even for non-mandatory files
        sys.stderr.write("Error parsing '%s': %s\n" %  (filename, reason))
        if mandatory:
            sys.stderr.write("Exiting.\n")
            sys.exit(1)
        else:
            raise

    return_list = []

    # Get the list of items (IDs) in the file and loop through them.
    for item_id in config.sections():
        item_dict = {}
        item_dict["id"] = item_id

        # Get the list of settings for this particular item.
        for option in config.options(item_id):

            # If this is a list ...
            if len(option) > 6 and option[-5:] == "_list":

                # Break it into elements separated by |.
                item_dict[option[:-5]] = [unicode(x.strip(), "UTF-8") for x in
                 config.get(item_id, option).split("|")]
	    
            else:

                # Otherwise, just grab the data.
                item_dict[option] = unicode(config.get(item_id, option).strip(),
                 "UTF-8")

        # Add this to the list of all objects we are returning.
        return_list.append(item_dict)

    return return_list

def DialogBox(message, screen, scalegfx, buttondict):
	boxx = 124*scalegfx
	boxy = 76*scalegfx
	boxw = 110*scalegfx
	boxh = 70*scalegfx
	bordermod = 2*scalegfx
	font = pygame.font.SysFont(None, 12 * scalegfx)
	newRect = pygame.Rect(boxx - bordermod, boxy - bordermod, boxw + (bordermod+bordermod), boxh + (bordermod+bordermod))
	AAfilledRoundedRect(screen, newRect, RED, 0.5)
	newRect = pygame.Rect(boxx, boxy, boxw, boxh)
	AAfilledRoundedRect(screen, newRect, DIALOG, 0.5)
	drawText(message, font, RED, screen, (126*scalegfx), (106*scalegfx))
	screen.blit(buttondict['surface'], buttondict['rect'])
	drawText('OK', font, RED, screen, (174*scalegfx), (131*scalegfx))


def AAfilledRoundedRect(surface,rect,color,radius=0.4):

    """
    AAfilledRoundedRect(surface,rect,color,radius=0.4)

    surface : destination
    rect    : rectangle
    color   : rgb or rgba
    radius  : 0 <= radius <= 1
    """

    rect         = Rect(rect)
    color        = Color(*color)
    alpha        = color.a
    color.a      = 0
    pos          = rect.topleft
    rect.topleft = 0,0
    rectangle    = Surface(rect.size,SRCALPHA)

    circle       = Surface([min(rect.size)*3]*2,SRCALPHA)
    draw.ellipse(circle,(0,0,0),circle.get_rect(),0)
    circle       = transform.smoothscale(circle,[int(min(rect.size)*radius)]*2)

    radius              = rectangle.blit(circle,(0,0))
    radius.bottomright  = rect.bottomright
    rectangle.blit(circle,radius)
    radius.topright     = rect.topright
    rectangle.blit(circle,radius)
    radius.bottomleft   = rect.bottomleft
    rectangle.blit(circle,radius)

    rectangle.fill((0,0,0),rect.inflate(-radius.w,0))
    rectangle.fill((0,0,0),rect.inflate(0,-radius.h))

    rectangle.fill(color,special_flags=BLEND_RGBA_MAX)
    rectangle.fill((255,255,255,alpha),special_flags=BLEND_RGBA_MIN)

    return surface.blit(rectangle,pos)



